package com.rongji.egov.fileupload.rjfile;

import com.rongji.egov.fileupload.RjFileProperties;
import com.rongji.egov.fileupload.domain.ResultMsgClient;
import com.rongji.egov.fileupload.packet.MsgRequestPacket;
import com.rongji.egov.fileupload.utils.Attributes;
import io.netty.channel.ChannelFuture;
import io.netty.util.Attribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/rjfile")
public class RjfileController {
    private static final Logger logger = LoggerFactory.getLogger(RjfileController.class);

    @Resource
    RjFileProperties properties;
    @Autowired
    private ResourceLoader resourceLoader;

    @GetMapping("/info")
    public Result info(){
        NettyFileClient client = new NettyFileClient("127.0.0.1", properties.getPort());
        ChannelFuture future;
        Result result = new Result();
        try{
            future = client.connect();
        } catch (Exception exception){
            result.setResult(false);
            result.setMsg(exception.getMessage());
            logger.error(result.getMsg(), exception);
            return result;
        }

        try {
            Attribute<ResultMsgClient> att = future.channel().attr(Attributes.MSG_C);
            ResultMsgClient msgResult = new ResultMsgClient();
            att.set(msgResult);

            MsgRequestPacket pingPack = new MsgRequestPacket("ping");
            future.channel().writeAndFlush(pingPack);

            synchronized (msgResult){
                try {
                    msgResult.wait(10000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }

            if(!msgResult.isFinish()){
                future.channel().close();
                String msg = String.format("服务端连接超时！%s:%s","127.0.0.1", properties.getPort());
                logger.error(msg);
                result.setResult(false);
                result.setMsg(msg);
                return result;
            }
            if(!msgResult.isSuccess()){
                String msg = String.format("服务端异常%s:%s。%s","127.0.0.1", properties.getPort(), msgResult.getMsg());
                logger.error(msg,  msgResult.getThrowable());
                result.setResult(false);
                result.setMsg(msg);
                return result;
            } else {
                org.springframework.core.io.Resource resource =
                        resourceLoader.getResource("classpath:version.txt");
                try {
                    InputStream inputStream = resource.getInputStream();
                    ByteArrayOutputStream versionStream = new ByteArrayOutputStream();
                    byte[] buffer = new byte[128];
                    int length;
                    while ((length = inputStream.read(buffer)) != -1) {
                        versionStream.write(buffer, 0, length);
                    }
                    String str = versionStream.toString(StandardCharsets.UTF_8.name());
                    result.setVersion(str);
                } catch (IOException e) {
                    result.setVersion("取版本信息出错，请查看日志");
                    logger.error("取版本信息出错", e);
                }

                result.setResult(true);
                String msg = String.format("端口：%s，存储路径:%s。",properties.getPort(), properties.getPath());
                result.setMsg(msg);
                return result;
            }
        }finally {
            future.channel().close();
            client.destroy();
        }
    }

}
